package com.franklin.ideaplugin.api.utils.psi;

import cn.hutool.core.util.StrUtil;
import com.intellij.psi.PsiMethod;
import com.intellij.psi.PsiParameter;
import com.intellij.psi.PsiParameterList;
import com.intellij.psi.PsiType;
import org.jetbrains.annotations.NotNull;

import java.util.List;
import java.util.stream.Collectors;
import java.util.stream.IntStream;

/**
 * @author Franklin
 * @since 2023/12/30 23:34
 */
public class PsiMethodUtils {

    /**
     * 获取方法的全名
     * @param psiMethod
     * @return
     */
    public static String getMethodQualifiedName(PsiMethod psiMethod){
        String prefix = PsiClassUtils.resolveContainingClassQualifiedName(psiMethod);
        if (StrUtil.isNotBlank(prefix)){
            prefix = prefix + "#";
        }
        return prefix + psiMethod.getName();
    }

    /**
     * 构建带参数方法全类名
     * @param psiMethod
     * @return
     */
    public static String getMethodQualifiedNameWithParameters(PsiMethod psiMethod){
        String methodQualifiedName = getMethodQualifiedName(psiMethod);
        List<PsiParameter> psiParameterList = getPsiMethodParameters(psiMethod);
        String paramType = psiParameterList.stream()
                .map(PsiParameter::getType)
                .map(PsiType::getCanonicalText)
                .collect(Collectors.joining(","));
        return methodQualifiedName + String.format("(%s)", paramType);
    }

    /**
     * 获取方法的参数
     * @param psiMethod
     * @return
     */
    public static List<PsiParameter> getPsiMethodParameters(@NotNull PsiMethod psiMethod){
        PsiParameterList parameterList = psiMethod.getParameterList();
        return IntStream.range(0,parameterList.getParametersCount())
                .mapToObj(parameterList::getParameter)
                .collect(Collectors.toList());
    }

    /**
     * 获取方法简称
     * @param psiMethod
     * @return
     */
    public static String getMethodSimpleName(PsiMethod psiMethod){
        String prefix = PsiClassUtils.resolveContainingClassSimpleName(psiMethod);
        if (StrUtil.isNotBlank(prefix)){
            prefix = prefix + "#";
        }
        return prefix + psiMethod.getName();
    }

}
